package com.weme.live.ext

import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.inputmethod.InputMethodManager
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weme.chat.bean.GiftMessage
import com.weme.chat.bean.toMap
import com.weme.common.BuildConfig
import com.weme.common.arouter.ARouterHelper
import com.weme.common.dialog.GiftSendSuccessDialog
import com.weme.common.dialog.RechargeDialog
import com.weme.common.dialog.RechargeDialogCallback
import com.weme.common.manager.SocketConnectManager
import com.weme.common.manager.SocketConnectManager.matchLiveData
import com.weme.common.network.FinishLiveRoomActivity
import com.weme.common.network.FollowBean
import com.weme.common.util.*
import com.weme.live.activity.LiveRoomActivity
import com.weme.live.activity.liveview.Message
import com.weme.live.view.GuideConsumptionView
import dev.kratos.api.im_server.v1.GetChannelInfoReply
import dev.kratos.api.im_server.v1.GetRtcTokenReply
import dev.kratos.api.im_server.v1.HangUpVideoReply
import dev.kratos.api.im_server.v1.TranslateReply
import dev.kratos.api.user_server.v1.GetAccountInfoReply
import dev.kratos.api.user_server.v1.GiftInfo
import dev.kratos.api.user_server.v1.SendGiftReply
import dev.kratos.api.user_server.v1.Users
import io.agora.CallBack
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.CustomMessageBody

//var isInputMsg = false
fun LiveRoomActivity.viewModeObserve() {
    getViewModel().navigateToReviewPageLiveData.observe(this) {
        getViewModel().putHangUp()
    }
    getViewModel().switchCamera.observe(this) {
        mRtcEngine?.switchCamera()
    }
    getViewModel().sendMsgContentLiveData.observe(this) {
        if (!getViewModel().isFictitious) {
            sendChatMsg(it.content)
        }
    }
    getViewModel().setInputMsgLiveData.observe(this) {
        getViewBinding().imGift.alpha = if (it.isEmpty()) 0.5f else 1f
    }
    LiveEventBus.get<Any>(LiveConfig.NET_WORK_LIVE).observe(this) {
        when (it) {
            is GetRtcTokenReply -> {}//应该没用 如果进入房间 没有token 才会调用此方法 这个接口 少房间名称
            is HangUpVideoReply -> {//收到关闭房间的推送
                hangUpVideo()

            }

            is Users -> {//获取主播信息
                getViewModel().anchorUser = it
                getViewModel().updateUserInfoLiveData.postValue(it) // getViewModel().followLiveData.postValue(it.isFollow == 1)
            }

            is SendGiftReply -> {//发送礼物
                sendGiftSuccess(it)
            }

            is TranslateReply -> {//翻译
                it.contentList.forEach {
                    getViewModel().translateMsgContentLiveData.postValue(it)
                }
            }

            is FinishLiveRoomActivity -> finish()//关闭房间出错的关闭房间

            is GetChannelInfoReply -> {// 应该是没用到
                Log.e("chatRoom", "http" + chatRoomId.toString())
//             chatRoomId = it.chatRoomId
//
//             if (!TextUtils.isEmpty(chatRoomId)) { //如果有roomid 加入聊天室
//                 addChat()
//             }
            }
            is FollowBean->{
                getViewModel().followLiveData.postValue(true) // showToast(resources.getString(com.example.resources.R.string.followed))
                addFollow()
            }

        }
    }


    getViewModel().updateAccountLiveData.observe(this) {
        getViewBinding().tvBalance.text = it.coins.toString()
    }
    getViewBinding().scvBalance.setOnFastClickListener {
        RechargeDialog.show(this, object : RechargeDialogCallback {
            override fun sendGiftInfo(giftInfo: GiftInfo) {

            }
        })
    }

    LiveEventBus.get<Any>(LiveConfig.NET_WORK_CALL).observe(this) {
        if (it is HangUpVideoReply) { //
            if (!getViewModel().isMatch) { //如果不是匹配电话 进入评价
                getViewModel().isSednMsg()
                getViewModel().anchorUser?.apply {
                    ARouterHelper.navigateToLiveEvaluateActivity(
                        this@viewModeObserve,
                        getViewModel().channelName,
                        getViewModel().liveDuration,
                        this
                    )
                }
            }
            finish()
            chatRoomListener()
        }
    }

    LiveEventBus.get<Any>(LiveConfig.NET_WORK_MINE).observe(this) {
        if (it is GetAccountInfoReply) {
            UserMKHelper.encode(UserMKHelper.VIP_LEVEL, it.vipLevel)
            SocketConnectManager.accountLiveData.postValue(it.account)
            if (getViewModel().isFictitious) {

                if (it.vipLevel == 0) { //未订阅 弹出订阅引导
                    guideConsumptionView = GuideConsumptionView(this)
                    getViewBinding().calView.addView(guideConsumptionView)
                    guideConsumptionView?.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        this.topToTop = getViewBinding().guideTime.id
                        this.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                    }
                    guideConsumptionView?.setTypeUi(false)
                } else if (it.account.payCount == 0) { //充值引导
                    guideConsumptionView = GuideConsumptionView(this)
                    getViewBinding().calView.addView(guideConsumptionView)
                    guideConsumptionView?.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        this.topToTop = getViewBinding().guideTime.id
                        this.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                    }
                    guideConsumptionView?.setTypeUi(true)
                }

            }


        }
    }
    SocketConnectManager.accountLiveData.observe(this) {
        getViewModel().updateAccountLiveData.postValue(it)
        getViewModel().account = it
        it?.let {
            if (!getViewModel().isMatch) {
                if (getViewModel().checkCoinSufficientForNextMinute(getViewModel().retrieveCallConfig()) && getViewModel().liveDuration > 0) { //当前金币少于下一分钟 需要提示
                    getViewModel().finalCountdownLiveData.postValue(60 - (getViewModel().liveDuration % 60))
                    getViewModel().isCallEndingNotifier = true
                    Log.e("live", "显示快没钱的倒计时")
                } else {
                    getViewModel().finalCountdownLiveData.postValue(-1)
                    getViewModel().isCallEndingNotifier = false
                }
            }


        }


    }
}

//退出房间操作
fun LiveRoomActivity.hangUpVideo() {
    if (getViewModel().isMatch) { //如果是匹配 回匹配界面
        if (getViewModel().isFictitious) {
            if (UserMKHelper.decodeInt(UserMKHelper.VIP_LEVEL) == 0) {
                showToast("跳转订阅商城")
            } else if (getViewModel().account?.payCount == 0) {
                RechargeDialog.show(this, object : RechargeDialogCallback {
                    override fun sendGiftInfo(giftInfo: GiftInfo) {

                    }

                })
            }
        } else { //如果是匹配并且不是营销视频
            getViewModel().account?.apply {
                if (this.pairCards > 0L || this.coins >= getViewModel().retrieveCallConfig().matchCall) {
                    matchLiveData.postValue("")
                } else {
                    showToast("跳转金币商城")
                    if (BuildConfig.DEBUG) {
                        showToast("匹配卡和金币都不够 直接返回")
                    }
                }
            }
        }
        finish()
    } else {
        getViewModel().anchorUser?.apply {
            ARouterHelper.navigateToLiveEvaluateActivity(
                this@hangUpVideo,
                getViewModel().channelName,
                getViewModel().liveDuration,
                this
            )
        }
        finish()
    }
}

fun LiveRoomActivity.sendGiftSuccess(it: SendGiftReply) {
    if (TextUtils.isEmpty(it.gift.giftUrl)) {
        val giftSendSuccessDialog = GiftSendSuccessDialog(
            getViewModel().anchorUser!!.nickname,
            getViewModel().anchorUser!!.headPic
        )
        giftSendSuccessDialog.show(this.supportFragmentManager, "GiftSendSuccessDialog")
    } else {
        getViewBinding().playerView.loadVideoFromAssets(it.gift.giftName + ".mp4", it.gift.md5) {
            downloadMp4(it.gift.giftUrl, it.gift.giftName) { isDow ->
                if (isDow == true) {
                    getViewBinding().playerView.loadVideoFromAssets(
                        it.gift.giftName + ".mp4",
                        it.gift.md5
                    ) {

                    }
                }

            }
        }
    }
    sendGiftSuccessSendMsg(it)
}

fun LiveRoomActivity.sendGiftSuccessSendMsg(it: SendGiftReply) {
    getViewModel().sendMsgLiveData.postValue(
        Message(
            avatarUrl = UserMKHelper.decodeString(
                UserMKHelper.HEADPIC
            ),
            nickname = UserMKHelper.decodeString(UserMKHelper.NAME),
            it.gift.giftName,
            true,
            type = 2
        )
    )
    if (getViewModel().isFictitious) { //虚拟主播 不发im消息
        val customMessage =
            ChatMessage.createSendMessage(ChatMessage.Type.CUSTOM) // 设置聊天类型为群聊。默认为单聊 `Chat`，也可以设置为聊天室 `ChatRoom`。 // 设置聊天类型为群聊。默认为单聊 `Chat`，也可以设置为聊天室 `ChatRoom`。
        val event = AgoraClient.EVENT_TYPING_GIFT
        val customBody = CustomMessageBody(event)
        val giftMessage = GiftMessage(it.gift.giftIcon, it.gift.giftUrl, it.gift.giftName)
        val giftMessageMap = giftMessage.toMap()
        customBody.params = giftMessageMap
        customMessage.addBody(customBody)
        customMessage.to = chatRoomId
        customMessage.chatType =
            ChatMessage.ChatType.ChatRoom // 发送消息时可以设置 `CallBack` 的实例来获得消息发送的状态。可以在该回调中更新消息的显示状态，例如消息发送失败后的提示等。
        customMessage.setMessageStatusCallback(object : CallBack {
            override fun onSuccess() { //showToast("发送消息成功");
                val inputMethodManager =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.hideSoftInputFromWindow(getViewBinding().calView.windowToken, 0)
            }

            override fun onError(code: Int, error: String) { //showToast("发送消息失败");
                Log.e("chat", "$code/$error")
            }
        })
        ChatClient.getInstance().chatManager().sendMessage(customMessage)
    }
}